package com.heima.wemedia.service.impl;

import com.alibaba.nacos.common.utils.UuidUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMeterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.management.VMManagement;
import sun.misc.VM;
import sun.rmi.log.LogHandler;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @author ybw
 * @version 1.0
 * @date 2021/12/13 17:57
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial>
    implements WmMaterialService {
  @Autowired private FileStorageService fileStorageService;
  @Autowired private WmMaterialMapper wmMaterialMapper;
  @Autowired private WmNewsMaterialMapper wmNewsMaterialMapper;
  /**
   * 上传素材
   *
   * @param multipartFile
   */
  @Override
  public ResponseResult uploadPicture(MultipartFile multipartFile) {
    // 校验参数
    if (multipartFile == null || multipartFile.getSize() == 0) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    String fileName = multipartFile.getOriginalFilename();
    // 获取后缀名
    String suffix = fileName.substring(fileName.lastIndexOf("."));
    String fileUrl = null;
    try {
      // 获取输入流
      InputStream is = multipartFile.getInputStream();
      // 避免重名
      String uuid = UuidUtils.generateUuid().replaceAll("-", "");
      fileName = uuid + suffix;
      fileUrl = fileStorageService.uploadImgFile("", fileName, is);
      log.info("文件上传成功");
    } catch (IOException e) {
      e.printStackTrace();
      log.error("文件上传失败");
    }
    // 封装成对象
    WmMaterial wmMaterial = new WmMaterial();
    wmMaterial.setUrl(fileUrl);
    wmMaterial.setCreatedTime(new Date());
    wmMaterial.setType((short) 0);
    // 从本地线程中获取用户id
    WmUser user = WmThreadLocalUtil.getUser();
    wmMaterial.setUserId(user.getId());
    wmMaterial.setIsCollection((short) 0);
    // 存入数据库
    wmMaterialMapper.insert(wmMaterial);
    return ResponseResult.okResult(wmMaterial);
  }

  /**
   * 素材列表
   *
   * @param wmMeterialDto
   * @return
   */
  @Override
  public ResponseResult picList(WmMeterialDto wmMeterialDto) {
    // 校验参数
    if (ObjectUtils.isEmpty(wmMeterialDto)) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    // 获取用户id
    Integer loginUserId = WmThreadLocalUtil.getUser().getId();
    // 获取收藏参数
    Short isCollection = wmMeterialDto.getIsCollection();

    // 获取分页参数
    Integer page = wmMeterialDto.getPage();
    Integer size = wmMeterialDto.getSize();
    // 根据用户id查询素材库
    LambdaQueryWrapper<WmMaterial> qw = new LambdaQueryWrapper<>();
    qw.eq(WmMaterial::getUserId, loginUserId).orderByDesc(WmMaterial::getCreatedTime);
    if (isCollection == 1) {
      qw.eq(WmMaterial::getIsCollection, isCollection);
    }
    IPage materialPage = new Page(page.longValue(), size.longValue());
    List records = page(materialPage, qw).getRecords();
    // 封装返回值对象
    PageResponseResult pageResponseResult = new PageResponseResult(page, size, records.size());
    pageResponseResult.setData(records);
    return pageResponseResult;
  }

  /**
   * 删除图片
   *
   * @param id
   * @return
   */
  @Override
  public ResponseResult delPic(Integer id) {
    // 校验参数
    if (id == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    // 根据图片id查询图片信息
    WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
    if (ObjectUtils.isEmpty(wmMaterial)) {
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
    // 根据图片id查询图片引用表
    LambdaQueryWrapper<WmNewsMaterial> qw = new LambdaQueryWrapper<>();
    qw.eq(WmNewsMaterial::getMaterialId, id);
    Integer count = wmNewsMaterialMapper.selectCount(qw);
    if (count > 0) {
      // 有引用则不能删除
      return ResponseResult.errorResult(501, "数据删除失败");
    }
    // 获取图片url
    String imgUrl = wmMaterial.getUrl();
    try {
      // minio删除图片
      fileStorageService.delete(imgUrl);
      // 数据库删除图片
      wmMaterialMapper.deleteById(id);
      log.info("删除图片成功");
    } catch (Exception e) {
      e.printStackTrace();
      log.error("文件删除失败");
      return ResponseResult.errorResult(500, "文件删除失败");
    }
    return ResponseResult.okResult(200, "操作成功");
  }

  /**
   * 收藏与取消收藏
   *
   * @param id
   * @param type 1 收藏， 0 取消
   * @return
   */
  @Override
  public ResponseResult collect(Integer id, int type) {
    // 校验参数
    if (id == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    try {
      // 根据type修改数据库
      WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
      wmMaterial.setIsCollection((short) type);
      wmMaterialMapper.updateById(wmMaterial);
    } catch (Exception e) {
      e.printStackTrace();
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
    return ResponseResult.okResult(200, "操作成功");
  }
}
